package com.yisu.expressway.manager.website.controller.goodsArchives;

import com.google.common.collect.Lists;
import com.yisu.expressway.ewf.common.web.JsonResult;
import com.yisu.expressway.ewf.entity.GoodsArchives;
import com.yisu.expressway.ewf.entity.GoodsSpecification;
import com.yisu.expressway.ewf.entity.SpecificationGoods;
import com.yisu.expressway.manager.core.service.IGoodsArchivesService;
import com.yisu.expressway.manager.core.service.IGoodsSpecificationService;
import com.yisu.expressway.manager.core.service.ISpecificationGoodsService;
import com.yisu.expressway.manager.domain.request.GoodsSpecificationRequest;
import com.yisu.expressway.manager.website.controller.BaseController;
import org.apache.calcite.linq4j.Linq4j;
import org.apache.calcite.linq4j.function.Function1;
import org.apache.calcite.linq4j.function.Predicate1;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.math.BigDecimal;
import java.util.List;

import static com.yisu.expressway.ewf.common.enums.ResponseCode.FAILURE;
import static com.yisu.expressway.ewf.common.enums.ResponseCode.SUCCESS;

/**
 * Created by xlt on 2017/4/25.
 */
@Controller
@RequestMapping(value = "/goodsSpecification")
public class GoodsSpecificationController extends BaseController {
    @Resource
    private IGoodsSpecificationService iGoodsSpecificationService;
    @Resource
    private IGoodsArchivesService iGoodsArchivesService;
    @Resource
    private ISpecificationGoodsService iSpecificationGoodsService;

    /**
     * 添加商品规格
     *
     * @param goodsSpecificationRequest 商品档案信息
     * @return 状态
     */
    @RequestMapping(value = "/getGoodsSpecificationList.json", produces = "application/json; charset=utf-8")
    @ResponseBody
    public JsonResult getGoodsSpecificationList(HttpServletRequest request, GoodsSpecificationRequest goodsSpecificationRequest) {
        try {
            if (StringUtils.isEmpty(goodsSpecificationRequest.getCategoryCode()) || StringUtils.isEmpty(goodsSpecificationRequest.getGoodsNo() + "")) {
                return new JsonResult(FAILURE.code, "参数不完整！");
            }
            List<GoodsSpecification> goodsSpecificationList = iGoodsSpecificationService.getGoodsSpecificationListByCategoryCodeAndGoodsNo(goodsSpecificationRequest);
            if (goodsSpecificationList != null && goodsSpecificationList.size() > 0) {
                return new JsonResult(drowTable(goodsSpecificationList));
            } else {
                return new JsonResult("");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return new JsonResult(FAILURE.code, "网络君泡妞去了.....");
        }
    }

    /**
     * 添加商品规格
     *
     * @param goodsSpecificationRequest 商品档案信息
     * @return 状态
     */
    @RequestMapping(value = "/resetGoodsSpecificationAction.json", produces = "application/json; charset=utf-8")
    @ResponseBody
    public JsonResult resetGoodsSpecificationAction(HttpServletRequest request, GoodsSpecificationRequest goodsSpecificationRequest) {
        try {
            if (StringUtils.isEmpty(goodsSpecificationRequest.getCategoryCode()) || StringUtils.isEmpty(goodsSpecificationRequest.getGoodsNo() + "")) {
                return new JsonResult(FAILURE.code, "参数不完整！");
            }
            if (iGoodsSpecificationService.resetGoodsSpecification(goodsSpecificationRequest)) {
                return new JsonResult(SUCCESS.code, "操作成功！");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return new JsonResult(FAILURE.code, "网络君泡妞去了.....");
    }

    /**
     * 添加商品规格
     *
     * @param goodsSpecificationRequest 商品档案信息
     * @return 状态
     */
    @RequestMapping(value = "/modifyGoodsSpecificationAction.json", produces = "application/json; charset=utf-8")
    @ResponseBody
    public JsonResult modifyGoodsSpecificationAction(HttpServletRequest request, GoodsSpecificationRequest
            goodsSpecificationRequest) {
        try {
            if (StringUtils.isEmpty(goodsSpecificationRequest.getBelongGroupName()) || StringUtils.isEmpty(goodsSpecificationRequest.getCategoryCode()) || StringUtils.isEmpty(goodsSpecificationRequest.getGoodsNo() + "")) {
                return new JsonResult(FAILURE.code, "参数不完整！");
            }
            GoodsArchives goodsArchives = iGoodsArchivesService.getGoodsArchivesByGoodsNo(goodsSpecificationRequest.getGoodsNo());
            if (goodsArchives == null) {
                return new JsonResult(FAILURE.code, "请先保存商品基础信息！");
            }
            /**
             * 前期校验控制，
             * 1.如果已经添加了规格商品，则规格不允许在变更，只能重置所有商品规格及商品
             * 2.目前只能限制两级规格分类
             */
            SpecificationGoods specificationGoods = new SpecificationGoods();
            specificationGoods.setGoodsNo(goodsSpecificationRequest.getGoodsNo());
            specificationGoods.setCategoryCode(Long.valueOf(goodsSpecificationRequest.getCategoryCode()));
            List<SpecificationGoods> specificationGoodsList = iSpecificationGoodsService.getSpecificationGoodsListByGoodsNoAndCategoryCode(specificationGoods);
            if (specificationGoodsList != null && specificationGoodsList.size() > 0) {
                return new JsonResult(FAILURE.code, "当前规格已经存在售卖的商品，不允许再次变更，如需要，请重置商品规格！");
            }
            List<GoodsSpecification> goodsSpecificationList = iGoodsSpecificationService.getGoodsSpecificationListByCategoryCodeAndGoodsNo(goodsSpecificationRequest);
            //获取最大等级分类
            GoodsSpecification maxLevelModel = Linq4j.asEnumerable(goodsSpecificationList).orderByDescending(new Function1<GoodsSpecification, Comparable>() {
                @Override
                public Comparable apply(GoodsSpecification goodsSpecification) {
                    return goodsSpecification.getLevel();
                }
            }).firstOrDefault();
            if (maxLevelModel != null && maxLevelModel.getLevel() >= 2) {
                return new JsonResult(FAILURE.code, "目前系统限制，最多允许两级规格！");
            }
            if (iGoodsSpecificationService.modifyGoodsSpecification(goodsSpecificationRequest)) {
                goodsSpecificationList = iGoodsSpecificationService.getGoodsSpecificationListByCategoryCodeAndGoodsNo(goodsSpecificationRequest);
                if (goodsSpecificationList != null && goodsSpecificationList.size() > 0) {
                    return new JsonResult(drowTable(goodsSpecificationList));
                }
            } else {
                return new JsonResult(FAILURE.code, "网络君泡妞去了.....");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return new JsonResult(FAILURE.code, "网络君泡妞去了.....");
    }


    private String drowTable(List<GoodsSpecification> goodsSpecificationList) {
        StringBuilder htmlBuilder = new StringBuilder();


        //获取最大等级分类
        GoodsSpecification maxLevelModel = Linq4j.asEnumerable(goodsSpecificationList).orderByDescending(new Function1<GoodsSpecification, Comparable>() {
            @Override
            public Comparable apply(GoodsSpecification goodsSpecification) {
                return goodsSpecification.getLevel();
            }
        }).firstOrDefault();
        Integer rowspan = maxLevelModel.getLevel();
        List<GoodsSpecification> levelOne = Linq4j.asEnumerable(goodsSpecificationList).where(new Predicate1<GoodsSpecification>() {
            @Override
            public boolean apply(GoodsSpecification goodsSpecification) {
                return goodsSpecification.getLevel().equals(1);
            }
        }).toList();
        List<GoodsSpecification> levelTwo = Linq4j.asEnumerable(goodsSpecificationList).where(new Predicate1<GoodsSpecification>() {
            @Override
            public boolean apply(GoodsSpecification goodsSpecification) {
                return goodsSpecification.getLevel().equals(2);
            }
        }).toList();
        List<GoodsSpecification> levelThree = Linq4j.asEnumerable(goodsSpecificationList).where(new Predicate1<GoodsSpecification>() {
            @Override
            public boolean apply(GoodsSpecification goodsSpecification) {
                return goodsSpecification.getLevel().equals(3);
            }
        }).toList();
        List<GoodsSpecification> levelFour = Linq4j.asEnumerable(goodsSpecificationList).where(new Predicate1<GoodsSpecification>() {
            @Override
            public boolean apply(GoodsSpecification goodsSpecification) {
                return goodsSpecification.getLevel().equals(4);
            }
        }).toList();
        SpecificationGoods specificationGoods = new SpecificationGoods();
        specificationGoods.setGoodsNo(levelOne.get(0).getGoodsNo());
        specificationGoods.setCategoryCode(Long.valueOf(levelOne.get(0).getCategoryCode()));
        List<SpecificationGoods> specificationGoodsList = iSpecificationGoodsService.getSpecificationGoodsListByGoodsNoAndCategoryCode(specificationGoods);
        if (specificationGoodsList == null)
            specificationGoodsList = Lists.newArrayList();
        switch (rowspan) {
            case 1:
                htmlBuilder.append("<table class=\"table table-hover table-striped table-bordered\">\n" +
                        "                                        <thead class=\"bordered-blueberry\">\n" +
                        "                                        <tr>\n" +
                        "                                            <th>\n" +
                        "                                                " + levelOne.get(0).getBelongGroupName() +
                        "                                            </th>\n" +
                        "                                            <th>\n" +
                        "                                                市场价格\n" +
                        "                                            </th>\n" +
                        "                                            <th>\n" +
                        "                                                价格\n" +
                        "                                            </th>\n" +
                        "                                            <th>\n" +
                        "                                                库存\n" +
                        "                                            </th>\n" +
                        "                                            <th>\n" +
                        "                                                销量\n" +
                        "                                            </th>\n" +
                        "                                            <th>\n" +
                        "                                                操作\n" +
                        "                                            </th>\n" +
                        "                                        </tr>\n" +
                        "                                        </thead>");

                htmlBuilder.append("<tbody>");
                int levelOneItemRowNum = 1;
                for (final GoodsSpecification levelOneItem : levelOne) {
                    SpecificationGoods currentGoodsModel = Linq4j.asEnumerable(specificationGoodsList).firstOrDefault(new Predicate1<SpecificationGoods>() {
                        @Override
                        public boolean apply(SpecificationGoods specificationGoods) {
                            return (specificationGoods.getSpecificationNo() + "").equals(levelOneItem.getSpecificationNo() + "") && (specificationGoods.getCategoryCode() + "").equals(levelOneItem.getCategoryCode() + "")
                                    && (specificationGoods.getGoodsNo() + "").equals(levelOneItem.getGoodsNo() + "");
                        }
                    });
                    if (currentGoodsModel == null) {
                        currentGoodsModel = new SpecificationGoods();
                        currentGoodsModel.setBazaarPrice(BigDecimal.valueOf(0));
                        currentGoodsModel.setPrice(BigDecimal.valueOf(0));
                        currentGoodsModel.setSalesVolume(Double.valueOf(0));
                        currentGoodsModel.setInventoryNum(Double.valueOf(0));
                    }
                    htmlBuilder.append("<tr>");
                    htmlBuilder.append("<td>" + levelOneItem.getName() + "</td>");
                    htmlBuilder.append("<td><input type=\"text\" class=\"form-control\" value=\"" + currentGoodsModel.getBazaarPrice() + "\" id=\"bazaarPrice_" + levelOneItemRowNum + "\" name=\"bazaarPrice_" + levelOneItemRowNum + "\" style=\"height: 34px; width:80px;\" ></td>");
                    htmlBuilder.append("<td><input type=\"text\" class=\"form-control\" value=\"" + currentGoodsModel.getPrice() + "\" id=\"price_" + levelOneItemRowNum + "\" name=\"price_" + levelOneItemRowNum + "\" style=\"height: 34px; width:80px;\" ></td>");
                    htmlBuilder.append("<td><input type=\"text\" class=\"form-control\" value=\"" + currentGoodsModel.getInventoryNum() + "\" id=\"inventoryNum_" + levelOneItemRowNum + "\" name=\"inventoryNum_" + levelOneItemRowNum + "\" style=\"height: 34px; width:80px;\" ></td>");
                    htmlBuilder.append("<td><input type=\"text\" class=\"form-control\"  value=\"" + currentGoodsModel.getSalesVolume() + "\" id=\"salesVolume_" + levelOneItemRowNum + "\" name=\"salesVolume_" + levelOneItemRowNum + "\" style=\"height: 34px; width:80px;\" ></td>");
                    htmlBuilder.append("<td><a href=\"javaScript:void(0)\" onclick=\"saveSpecificationGoods('" + levelOneItemRowNum + "','" + levelOneItem.getCategoryCode() + "','" + levelOneItem.getGoodsNo() + "','" + levelOneItem.getSpecificationNo() + "')\" class=\"btn btn-default btn-xs purple\"><i  class=\"fa fa-save\"></i>保存</a>\n");
                    htmlBuilder.append("</tr>");
                    levelOneItemRowNum++;
                }
                htmlBuilder.append("</tbody>");
                htmlBuilder.append("</table>");
                break;
            case 2:
                htmlBuilder.append("<table class=\"table table-hover table-striped table-bordered\">\n" +
                        "                                        <thead class=\"bordered-blueberry\">\n" +
                        "                                        <tr>\n" +
                        "                                            <th>\n" +
                        "                                                " + levelOne.get(0).getBelongGroupName() +
                        "                                            </th>\n" +
                        "                                            <th>\n" +
                        "                                                " + levelTwo.get(0).getBelongGroupName() +
                        "                                            </th>\n" +
                        "                                            <th>\n" +
                        "                                                市场价格\n" +
                        "                                            </th>\n" +
                        "                                            <th>\n" +
                        "                                                价格\n" +
                        "                                            </th>\n" +
                        "                                            <th>\n" +
                        "                                                库存\n" +
                        "                                            </th>\n" +
                        "                                            <th>\n" +
                        "                                                销量\n" +
                        "                                            </th>\n" +
                        "                                            <th>\n" +
                        "                                                操作\n" +
                        "                                            </th>\n" +
                        "                                        </tr>\n" +
                        "                                        </thead>");
                htmlBuilder.append("<tbody>");
                Integer editRowNum = levelTwo.size();
                for (final GoodsSpecification levelOneItem : levelOne) {
                    //找出第一级别下级分类
                    List<GoodsSpecification> underLevelOne = Linq4j.asEnumerable(levelTwo).where(new Predicate1<GoodsSpecification>() {
                        @Override
                        public boolean apply(GoodsSpecification goodsSpecification) {
                            return (goodsSpecification.getParentId() + "").equals(levelOneItem.getSpecificationNo() + "");
                        }
                    }).toList();
                    Integer underLevelOneItemRowNum = underLevelOne.size();
                    for (final GoodsSpecification underLevelOneItem : underLevelOne) {
                        SpecificationGoods currentGoodsModel = Linq4j.asEnumerable(specificationGoodsList).firstOrDefault(new Predicate1<SpecificationGoods>() {
                            @Override
                            public boolean apply(SpecificationGoods specificationGoods) {
                                return (specificationGoods.getSpecificationNo() + "").equals(underLevelOneItem.getSpecificationNo() + "") && (specificationGoods.getCategoryCode() + "").equals(underLevelOneItem.getCategoryCode() + "")
                                        && (specificationGoods.getGoodsNo() + "").equals(underLevelOneItem.getGoodsNo() + "");
                            }
                        });
                        if (currentGoodsModel == null) {
                            currentGoodsModel = new SpecificationGoods();
                            currentGoodsModel.setBazaarPrice(BigDecimal.valueOf(0));
                            currentGoodsModel.setPrice(BigDecimal.valueOf(0));
                            currentGoodsModel.setInventoryNum(Double.valueOf(0));
                            currentGoodsModel.setSalesVolume(Double.valueOf(0));
                        }
                        if (underLevelOneItemRowNum == underLevelOne.size()) {
                            htmlBuilder.append("<tr>");
                            htmlBuilder.append("<td rowspan=\"" + underLevelOne.size() + "\">" + levelOneItem.getName() + "</td>");
                            htmlBuilder.append("<td rowspan=\"1\">" + underLevelOneItem.getName() + "</td>");
                            htmlBuilder.append("<td> <input type=\"text\" class=\"form-control\" value=\"" + currentGoodsModel.getBazaarPrice() + "\" id=\"bazaarPrice_" + editRowNum + "\" name=\"bazaarPrice_" + editRowNum + "\" style=\"height: 34px; width:80px;\" ></td>");
                            htmlBuilder.append("<td> <input type=\"text\" class=\"form-control\" value=\"" + currentGoodsModel.getPrice() + "\" id=\"price_" + editRowNum + "\" name=\"price_" + editRowNum + "\" style=\"height: 34px; width:80px;\" ></td>");
                            htmlBuilder.append("<td><input type=\"text\" class=\"form-control\" value=\"" + currentGoodsModel.getInventoryNum() + "\" id=\"inventoryNum_" + editRowNum + "\" name=\"inventoryNum_" + editRowNum + "\" style=\"height: 34px; width:80px;\" ></td>");
                            htmlBuilder.append("<td> <input type=\"text\" class=\"form-control\" value=\"" + currentGoodsModel.getSalesVolume() + "\"  id=\"salesVolume_" + editRowNum + "\" name=\"salesVolume_" + editRowNum + "\" style=\"height: 34px; width:80px;\" ></td>");
                            htmlBuilder.append("<td><a href=\"javaScript:void(0)\" onclick=\"saveSpecificationGoods('" + editRowNum + "','" + underLevelOneItem.getCategoryCode() + "','" + underLevelOneItem.getGoodsNo() + "','" + underLevelOneItem.getSpecificationNo() + "')\" class=\"btn btn-default btn-xs purple\"><i  class=\"fa fa-save\"></i>保存</a>\n");
                            htmlBuilder.append("</tr>");
                        } else {
                            htmlBuilder.append("<tr>");
                            htmlBuilder.append("<td rowspan=\"1\">" + underLevelOneItem.getName() + "</td>");
                            htmlBuilder.append("<td> <input type=\"text\" class=\"form-control\" value=\"" + currentGoodsModel.getBazaarPrice() + "\" id=\"bazaarPrice_" + editRowNum + "\" name=\"bazaarPrice_" + editRowNum + "\" style=\"height: 34px; width:80px;\" ></td>");
                            htmlBuilder.append("<td> <input type=\"text\" class=\"form-control\" value=\"" + currentGoodsModel.getPrice() + "\"  id=\"price_" + editRowNum + "\" name=\"price_" + editRowNum + "\" style=\"height: 34px; width:80px;\" ></td>");
                            htmlBuilder.append("<td><input type=\"text\" class=\"form-control\" value=\"" + currentGoodsModel.getInventoryNum() + "\"  id=\"inventoryNum_" + editRowNum + "\" name=\"inventoryNum_" + editRowNum + "\" style=\"height: 34px; width:80px;\" ></td>");
                            htmlBuilder.append("<td> <input type=\"text\" class=\"form-control\" value=\"" + currentGoodsModel.getInventoryNum() + "\"   id=\"salesVolume_" + editRowNum + "\" name=\"salesVolume_" + editRowNum + "\" style=\"height: 34px; width:80px;\" ></td>");
                            htmlBuilder.append("<td><a href=\"javaScript:void(0)\" onclick=\"saveSpecificationGoods('" + editRowNum + "','" + underLevelOneItem.getCategoryCode() + "','" + underLevelOneItem.getGoodsNo() + "','" + underLevelOneItem.getSpecificationNo() + "')\" class=\"btn btn-default btn-xs purple\"><i  class=\"fa fa-save\"></i>保存</a>\n");
                            htmlBuilder.append("</tr>");
                        }
                        underLevelOneItemRowNum--;
                        editRowNum--;
                    }
                }
                htmlBuilder.append("</tbody>");
                htmlBuilder.append("</table>");
                break;

        }
        return htmlBuilder.toString();
    }
}
